package models

import (
	"fmt"
	"time"
)

type Reservation struct {
	Id           int       `json:"id"`
	EnterpriseId int       `json:"enterprise_id"`
	StaffId      int       `json:"staff_id"`
	Code         string    `json:"code"`
	GoodsTitle   string    `json:"goods_title"`
	GoodsIds     string    `json:"goods_ids"`
	Dikou        float64   `json:"dikou"`
	Money        float64   `json:"money"`
	ValidTime    time.Time `json:"valid_time"`
	Status       int       `json:"status"`
	CreateAt     time.Time `json:"create_at"`
	UpdateAt     time.Time `json:"update_at"`
}

func GetResers(page, limit int, status, code, comName string) (interface{}, *Paginator) {
	var res []*struct {
		Id         int       `json:"id"`
		Code       string    `json:"code"`
		GoodsTitle string    `json:"goods_title"`
		Dikou      string    `json:"dikou"`
		Money      string    `json:"money"`
		ValidTime  time.Time `json:"valid_time"`
		Status     int       `json:"status"`
		ComName    string    `json:"com_name"`
		CreateAt   time.Time `json:"create_at"`
	}
	m := DB.Table("enterprise_reservation er").
		Select("er.id,er.code,er.goods_title,er.dikou,er.money,er.valid_time,er.status,er.create_at,e.name as com_name").
		Joins("left join enterprise e on e.id = er.enterprise_id").
		Order("id DESC")

	if status != "" {
		m.Where("er.status = ? ", status)
	}
	if code != "" {
		m.Where("er.code = ? ", code)
	}
	if comName != "" {
		m.Where("e.name like ? ", fmt.Sprintf("%%%v%%", comName))
	}
	var count int
	m.Count(&count)
	paginate := NewPage(page, limit, count)

	err := m.Offset(paginate.Offset).Limit(paginate.Limit).Find(&res).Error
	if err != nil {
		return nil, nil
	}

	return res, &paginate
}

func ExistReserByID(id int) bool {
	var reser Reservation
	DB.Table("enterprise_reservation").Select("id").Where("id = ?", id).First(&reser)

	if reser.Id > 0 {
		return true
	}

	return false
}

func EditReserByID(id int, data interface{}) bool {
	err := DB.Table("enterprise_reservation").Where("id = ?", id).Updates(data)
	if err.Error != nil {
		return false
	}
	return true
}
